package com.lanlian.cayman.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;

import com.lanlian.cayman.HqMsg;
import com.lanlian.cayman.R;
import com.lanlian.cayman.fragment.MarketFragment;
import com.lanlian.cayman.fragment.ProfitLossOrdinaryFragment;
import com.lanlian.cayman.fragment.ProfitLossSeniorFragment;
import com.lanlian.cayman.utils.NumberManager;
import com.lanlian.commonlib.base.BaseActivity;
import com.lanlian.commonlib.bean.PositionDetailsInfo;
import com.lanlian.commonlib.data.GoodsBean;
import com.lanlian.commonlib.event.EventCode;
import com.lanlian.commonlib.event.EventMessage;
import com.lanlian.commonlib.util.OnEventID;
import com.lanlian.commonlib.util.OnEventUtils;
import com.lanlian.uikit.CustomDialog;
import com.lanlian.utillib.DisplayUtil;
import com.lanlian.utillib.NumberUtils;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;

import java.math.BigDecimal;
import java.util.ArrayList;

import static java.math.BigDecimal.ROUND_HALF_UP;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : huxiaobo@xlanlian.com
 *     date   : 2018/8/15 18:39
 *     desc   : 止盈止损操作页面
 *     version: 1.0
 * </pre>
 */
public class ProfitLossActivity extends BaseActivity implements View.OnClickListener {

    private MagicIndicator mMagicIndicator;
    private TextView mTvContractName;
    private TextView mTvDirection;
    private TextView mTvPrice;
    private TextView mTvOpenPrice;
    private ViewPager mViewPager;
    private TextView mTvAdd;
    private TextView mTvPositionNum;

    private String[] mTitleList = new String[]{"普通", "高级"};
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    public static int mAmount;
    private PositionDetailsInfo mPositionDetailsInfo;

    private boolean mIsFirst = true;
    private int count;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profit_loss, true);
        initData();
        initView();
        setListeners();
        initFragments();
        initNavigator();
        setPositionDetailsInfo();
    }

    @Override
    protected void initData() {
        super.initData();
        mPositionDetailsInfo = (PositionDetailsInfo) getIntent().getSerializableExtra("positionDetailsInfo");
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("止盈止损");
        setRightImage(R.mipmap.documentary_icon_problem);
        mMagicIndicator = findViewById(R.id.magic_indicator);
        mTvContractName = findViewById(R.id.tv_contract_name);
        mTvDirection = findViewById(R.id.tv_direction);
        mTvPrice = findViewById(R.id.tv_price);
        mViewPager = findViewById(R.id.view_pager);
        mTvAdd = findViewById(R.id.tv_add);
        mTvOpenPrice = findViewById(R.id.tv_open_price);
        mTvPositionNum = findViewById(R.id.tv_position_num);
    }

    @Override
    protected void setListeners() {
        super.setListeners();
        mTvAdd.setOnClickListener(this);
        mImgAction.setOnClickListener(this);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
            }

            @Override
            public void onPageSelected(int i) {
                if (i == 1 && mIsFirst) {
                    Dialog dialog = new CustomDialog(ProfitLossActivity.this, new CustomDialog.OnClickListener() {
                        @Override
                        public void onLeftClick() {
                            mViewPager.setCurrentItem(0);
                        }

                        @Override
                        public void onRightClick() {
                            mIsFirst = false;
                        }
                    }).setContent("如您选择启用高级止盈止损，代表您已熟悉该规则，并已了解使用规则可能带来的风险。").setTitle("温馨提醒");
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.show();
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });
    }

    private void initFragments() {
        mFragments.add(ProfitLossOrdinaryFragment.getInstance(mPositionDetailsInfo));
        mFragments.add(ProfitLossSeniorFragment.getInstance(mPositionDetailsInfo));
    }

    private void initNavigator() {
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return mTitleList == null ? 0 : mTitleList.length;
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                ColorTransitionPagerTitleView colorTransitionPagerTitleView = new ColorTransitionPagerTitleView(context);
                colorTransitionPagerTitleView.setNormalColor(getResources().getColor(R.color.color_K4));
                colorTransitionPagerTitleView.setTextSize(12);
                colorTransitionPagerTitleView.setSelectedColor(Color.WHITE);
                colorTransitionPagerTitleView.setText(mTitleList[index]);
                colorTransitionPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mViewPager.setCurrentItem(index);
                    }
                });
                return colorTransitionPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                float borderWidth = UIUtil.dip2px(context, 1);
                indicator.setLineHeight(DisplayUtil.dip2px(context, 36) - 2 * borderWidth);
                indicator.setYOffset(borderWidth);
                indicator.setRoundRadius(DisplayUtil.dip2px(context, 2));
                indicator.setColors(getResources().getColor(R.color.color_K4));
                return indicator;
            }
        });
        mMagicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mMagicIndicator, mViewPager);
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragments.get(position);
            }

            @Override
            public int getCount() {
                return mFragments.size();
            }
        });
    }

    private void setPositionDetailsInfo() {
        mTvContractName.setText(mPositionDetailsInfo.getContractName());
        mTvDirection.setText("1".equals(mPositionDetailsInfo.getcPositionFlag()) ? "买" : "卖");
        if ("1".equals(mPositionDetailsInfo.getcPositionFlag())) {
            mTvDirection.setTextColor(getResources().getColor(R.color.color_T7));
        } else {
            mTvDirection.setTextColor(getResources().getColor(R.color.color_T8));
        }
        GoodsBean goodsBean = MarketFragment.getRespMarket().getGoods(mPositionDetailsInfo.getVcContractCode());
        if (goodsBean != null) {
            count = NumberManager.getNumberDecimalDigits(goodsBean.minChange);
        } else {
            count = 2;
        }
        String averagePrice = NumberUtils.roundStr(mPositionDetailsInfo.getJj(), count + 1, BigDecimal.ROUND_HALF_UP);
        mTvOpenPrice.setText(averagePrice);
        mTvPrice.setText(mPositionDetailsInfo.getCurrentPrice());
        mTvPositionNum.setText(String.valueOf(mPositionDetailsInfo.getlCurrentAmount()));
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.img_action:
                OnEventUtils.onEvent(this, OnEventID.STOP_PNL_IMAGE);
                startActivity(new Intent(this, ProfitLossImageActivity.class));
                break;
            case R.id.tv_add:
                if (mAmount == 0) {
                    showToast("可设置手数为0");
                    return;
                }
                startActivity(new Intent(this, ProfitLossSetupActivity.class)
                        .putExtra("positionDetailsInfo", mPositionDetailsInfo)
                        .putExtra("isNew", true)
                        .putExtra("isOrdinary", mViewPager.getCurrentItem() == 0));
                break;
            default:
                break;
        }
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        super.onReceiveEvent(event);
        switch (event.getCode()) {
            case EventCode.EVENT_MARKET:
                HqMsg.YsHqInfo ysHqInfo = (HqMsg.YsHqInfo) event.getData();
                if (mPositionDetailsInfo.getVcContractCode().equals(ysHqInfo.getCommodityNo() + ysHqInfo.getContractNo1())) {
                    mPositionDetailsInfo.setCurrentPrice(NumberUtils.roundStr(ysHqInfo.getQLastPrice(), count, ROUND_HALF_UP));
                    mTvPrice.setText(mPositionDetailsInfo.getCurrentPrice());
                }
                break;
            default:
                break;
        }
    }
}
